package org.example.day03;

/**
 * 第二章节2.1.3:多个对象多个锁
 **/
public class MyThread4 {
    private int num = 0;

    //①添加了synchronized修饰实例方法，对象锁即this，线程g和h调用addI方法的是两个对象m41和m42，不会出现脏读。
    synchronized public void addI(String username) {
        try {
            if (username.equals("a")) {
                num = 100;
                System.out.println("a set over!");
                Thread.sleep(2000);
            } else {
                num = 200;
                System.out.println("b set over!");
            }
            System.out.println(username + " num = " + num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyThread4 m41 = new MyThread4();
        MyThread4 m42 = new MyThread4();
        ThreadG tg = new ThreadG(m41);
        tg.start();
        ThreadH th = new ThreadH(m42);
        th.start();
    }
}

class ThreadG extends Thread {
    private MyThread4 m4;
    public ThreadG(MyThread4 m4) {
        this.m4 = m4;
    }
    @Override
    public void run() {
        m4.addI("a");
    }
}

class ThreadH extends Thread {
    private MyThread4 m4;
    public ThreadH(MyThread4 m4) {
        this.m4 = m4;
    }
    @Override
    public void run() {
        m4.addI("b");
    }
}
